﻿using System;
using System.Collections.Generic;
using System.Linq;
using ComLib;
using ComLib.Data;
using ComLib.Web.Modules.Tags;


namespace ComLib.Web.Modules.Helpers
{
    /// <summary>
    /// DTO object for handling tags on any entity.
    /// </summary>
    public class TagsEntry
    {
        public string Tags;
        public int GroupId;
        public int RefId;
    }



    /// <summary>
    /// Helper class for Tags.
    /// </summary>
    public class TagHelper
    {
        /// <summary>
        /// Iterate over each widget/instance in the specified zone.
        /// </summary>
        /// <param name="zone"></param>
        /// <param name="executor"></param>
        public static List<Tag> ConvertToTags(string tagsAsString, int groupid, int refid)
        {
            if (string.IsNullOrEmpty(tagsAsString))
                return null;

            string[] tokens = tagsAsString.ToLower().Trim().Split(' ');
            if (tokens == null || tokens.Length == 0)
                return null;

            var tags = new List<Tag>();
            foreach (string token in tokens)
                tags.Add(new Tag() { GroupId = groupid, RefId = refid, Name = token });

            return tags;
        }


        /// <summary>
        /// Process the entries.
        /// </summary>
        /// <param name="itemsToProcess"></param>
        public static void ProcessQueue(IList<TagsEntry> itemsToProcess)
        {
            if (itemsToProcess == null || itemsToProcess.Count == 0)
                return;

            foreach (var entry in itemsToProcess)
            {
                string error = string.Format("Unable to apply tags for GroupId[{0}], RefId[{1}], Tags[{2}]", entry.GroupId, entry.RefId, entry.Tags);
                ExecuteHelper.TryCatchLog(error, () =>
                {
                    // Delete existing tags for the associated group/ref id combination.
                    Tag.Repository.Delete(Query<Tag>.New().Where(t => t.GroupId).Is(entry.GroupId)
                                                                  .And(t => t.RefId).Is(entry.RefId));

                    // Convert string to Tag objects.
                    List<Tag> tags = TagHelper.ConvertToTags(entry.Tags, entry.GroupId, entry.RefId);
                    if (tags != null && tags.Count > 0)
                    {
                        foreach (var tag in tags) Tag.Create(tag);
                    }
                });
            }
        }
    }
}
